import React from 'react';
import router from 'umi/router';

import { connect } from 'dva';

import { Button,Form, Input } from 'antd';

const FormItem = Form.Item;

const linePath = '/AccountConfig/ResBank';


@connect(({
  resBank, resCountryState
}) => ({
  resBank, resCountryState

}))
class FormCreate extends React.Component {
  state = {
  }

  id = 0

  async componentDidMount() {
    const { location: {query: { id } } } = this.props;
    this.id = Number(id)
    if (this.id) {
      const { dispatch } = this.props;
      await dispatch({
        type: 'resBank/view',
        payload:  { id: this.id }
      });

    }

    // 获取多对一字段的下拉列表框选项所需要的数据

    const { dispatch } = this.props;
    await dispatch({
      type: 'resCountryState/search',
      payload: {domain:[], fields:{} },
    });


  }

  handleSubmit = e => {
    const { dispatch, form } = this.props;
    e.preventDefault();

    const create_or_write = async (vals) => {
      if(this.id){
        await dispatch({
          type: 'resBank/write',
          payload : {
            id: this.id,  vals,
          },
        });

        router.push(`${linePath}?id=${this.id}`);
      }
      else{
        await dispatch({
          type: 'resBank/create',
          payload : {
            vals,
            fields:{}
          },
        });

        const { resBank:{record} } = this.props;

        if (record.id){
          router.push(`${linePath}?id=${record.id}`);
        }
      }

    }


    form.validateFieldsAndScroll( async (err, values) => {

      if (!err) {

        const vals = { ...values,
        };

        await create_or_write(vals)

      }
    });
  };


  render() {
    const { form: { getFieldDecorator }  } = this.props;
    const { resBank: { record } } = this.props;

    return (
      <div>
          <Form onSubmit={this.handleSubmit}>
            <FormItem style={{ marginTop: 32 }}>
              <Button type="primary" htmlType="submit" >提交
              </Button>
            </FormItem>

            <FormItem label="名称">
              {getFieldDecorator('name', {
                rules: [{ required: true }],
                initialValue: record.name ,
              })(
                <Input />
              )}
            </FormItem>

            <FormItem label="代码">
              {getFieldDecorator('bic', {
               // rules: [{ required: true }],
                initialValue: record.bic,
              })(
                <Input />
              )}
            </FormItem>

          </Form>


      </div>

    );
  }
}


export default Form.create()(FormCreate);


